import base64,pickle
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request,response,user):
    cart_cookie = request.COOKIES.get('cart_cookie')
    if cart_cookie is None:
        return response
    cart_dict = pickle.loads(base64.b64decode(cart_cookie))
    if cart_dict is None:
        return response
    # {'sku_id':{'count':1,'selected':True}}
    conn = get_redis_connection('cart')
    pl = conn.pipeline()
    for sku_id, sku_count in cart_dict.items():
        pl.hincrby('cart_%s' % user.id, sku_id, sku_count['count'])
        if sku_count['selected']:
            pl.sadd('cart_select_%s' % user.id, sku_id)
    pl.execute()

    response.delete_cookie('cart_cookie')
    return response